import { Button, Form, FormInstance, Input, Upload, UploadFile } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import React, { useEffect, useRef, useState } from "react";
import { RcFile, UploadProps } from "antd/lib/upload";
import useMessage from "@/hooks/useMessage";
import { uploadFile } from "@/api/modules/common";
import { User } from "@/api/interface";
import { updateUserInfo } from "@/api/modules/user";

interface PropsType {
	type?: string;
	user: User.UserInfo;
	onComfirm?: () => void;
}

const UserEdit: React.FC<PropsType> = props => {
	const { type, user } = props;
	const { contextHolder, success } = useMessage();

	const [fileList, setFileList] = useState<UploadFile[]>([]);

	const handleUploadImages = async () => {
		const formData = new FormData();
		fileList.forEach(file => {
			formData.append("file", file as RcFile);
		});
		const res = await uploadFile(formData);
		return res.data;
	};

	const fileUploadProps: UploadProps = {
		onRemove: file => {
			const index = fileList.indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			setFileList(newFileList);
		},
		beforeUpload: file => {
			setFileList([...fileList, file]);
			return false;
		},
		fileList
	};

	const onFinish = async (values: any) => {
		let user_image;
		if (fileList.length > 0) {
			const res = await handleUploadImages();
			user_image = res.images[0].imageUrl;
		}
		const form = {
			...values,
			user_image
		};
		updateUserInfo({ ...form, id: user.id });
		props.onComfirm && props.onComfirm();
		success("发布成功");
	};

	const formRef = useRef<FormInstance | null>(null);

	useEffect(() => {
		if (type) formRef.current?.resetFields();
	}, [user, fileList]);

	useEffect(() => {
		return () => {
			formRef.current?.setFieldsValue({
				title: "",
				classify: "",
				top: 0,
				tags: []
			});
		};
	});

	return (
		<div>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={user}
			>
				<Form.Item label="用户名" name="name">
					<Input />
				</Form.Item>
				<Form.Item label="个性签名" name="description">
					<Input.TextArea rows={4} />
				</Form.Item>
				<Form.Item label="头像" valuePropName="fileList">
					<Upload listType="picture-card" {...fileUploadProps}>
						<div>
							<PlusOutlined />
							<div style={{ marginTop: 8 }}>上传头像</div>
						</div>
					</Upload>
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default UserEdit;
